package com.martin.fastframe.ui.ceiling

import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import com.martin.lib_base.base.BaseViewHolder
import com.martin.lib_base.common.CommonAdapter
import com.martin.lib_base.interfaces.ITypeBean
import com.martin.lib_base.ktx.commonAdapter
import com.martin.lib_base.ktx.loge

class CeilingModel {

    private var currentViewHolder: BaseViewHolder<*, *>? = null
    private var currentIndex: Int = -1

    private var rv: RecyclerView? = null

    /**
     * 处理吸顶效果
     * 仅支持[LinearLayoutManager]
     * Adapter仅支持[CommonAdapter]
     */
    fun handleCeiling(rv: RecyclerView) {
        rv.post {
            this.rv = rv
            val layoutManager = rv.layoutManager as LinearLayoutManager
            val adapter = rv.commonAdapter()!!
            rv.addOnScrollListener(object : OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    loge("滚动监听 : $dy")
                    // 获取第一个可见的item位置
                    val visibleItemPosition = layoutManager.findFirstVisibleItemPosition()
                    // 完全可见位置
                    val completelyVisibleItemPosition =
                        layoutManager.findFirstCompletelyVisibleItemPosition()

                    // 吸顶View为null,则创建
                    if (currentViewHolder == null) {
                        // 判断第一个可见item是吸顶类型
                        if (adapter.getItemViewType(visibleItemPosition) == ITypeBean.ITEM_TYPE_CEILING) {
                            currentViewHolder =
                                adapter.createViewHolder(
                                    rv,
                                    adapter.getItemViewType(visibleItemPosition)
                                )
                            val viewGroup = rv.parent as ViewGroup

                            // 将View添加到视图中
                            viewGroup.addView(currentViewHolder!!.itemView)
                        }
                    } else {
                        val itemView = currentViewHolder!!.itemView
                        if (dy > 0) {
                            // 向上滑动
                            if (itemView.top > 0) {
                                val mostTranslationY =
                                    dy.toFloat().coerceAtMost(-itemView.top.toFloat())
                                itemView.translationY = mostTranslationY
                            }

                        } else {
                            // 向下滑动

                        }
                    }
                }
            })
        }
    }

}